package muse.widgets;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import muse.Launcher;

public class TextboxWidget extends Widget {
	private Toolkit tk = Toolkit.getDefaultToolkit();
	private Image textboxImg = tk.getImage(getClass().getClassLoader()
			.getResource("muse/resources/muse_textBox_dummy.png"));
	private JTextArea textArea;
	private String[] messages;
	private int index;
	private JPanel all;
	private final JButton prev = new JButton(), next = new JButton();

	public TextboxWidget() {
		this.setLayout(new BorderLayout());	
		setPreferredSize(new Dimension(320,90));

		textArea = new JTextArea();
		textArea.setEditable(false);
		textArea.setBackground(null);
		textArea.setOpaque(false);
		textArea.setLineWrap(true);
		textArea.setWrapStyleWord(true);
		textArea.setVisible(true);
		textArea.setSize(250, 90);
		textArea.setLocation(40, 30);
		textArea.setText("I believe I can impress you in a hundred different ways! Are you impressed yet?");
		Random rng = new Random();
		textArea.setText(Launcher.greetings[rng.nextInt(4)]);
		all = new JPanel() {
			public void paintComponent(Graphics g) {
				g.drawImage(textboxImg, 0, 0, getWidth(), getHeight(), null);
			}
		};
		all.setPreferredSize(new Dimension(250,90));
		all.add(textArea);
		this.add(all, BorderLayout.CENTER);		
		
		setMessage(new String[] {"Unfinished text... Tell Peter about this."});
		prev.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				index--;
				if(index == 0)
					prev.setEnabled(false);
				next.setEnabled(true);
				textArea.setText(messages[index]);
			}
		});
		next.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				index++;
				if(index == messages.length - 1)
					next.setEnabled(false);
				prev.setEnabled(true);
				textArea.setText(messages[index]);
			}
		});
		add(prev, BorderLayout.WEST);
		add(next, BorderLayout.EAST);
	}
	
	public void addToPanel(Component c) {
		all.add(c);
	}
	public void removeFromPanel(Component c) {
		all.remove(c);
	}
	public void removeAllFromPanel() {
		ArrayList<Component> toKill = new ArrayList<Component>();
		for(Component c : all.getComponents())
			if(!(c instanceof JTextArea))
				toKill.add(c);
		for(Component c : toKill)
			all.remove(c);
	}

	public void setMessage(String[] s) {
		index = 0;
		prev.setEnabled(false);
		if(s.length == 1 || s.length == 0)
			next.setEnabled(false);
		else next.setEnabled(true);
		//textArea.setText("");
		if(s.length > 0)
			textArea.setText(s[0]);
		messages = s;
	}

	@Override
	public String getIcon() {
		return "";
	}

}
